<?php

require_once(dirname(__FILE__).'/Constants.php');
require_once(dirname(__FILE__).'/Config.php');
require_once(dirname(__FILE__).'/DB.php');
require_once(dirname(__FILE__).'/Util.php');

class Invite {
    public $id;
    public $owner_id;
    public $target_date;
    public $message = '';
    public $fixed   = 0;
    public $via     = '';
    public $members = array();
    public $create_stamp;
    
    function __construct ($invite_id = '') {
        if (!$invite_id) return;
        
        $dbh = DB::load_dbh();
        
        $result = mysql_query(sprintf('
            SELECT
                invite_id,
                target_date,
                message,
                fixed,
                via,
                create_stamp
            FROM
                invites
            WHERE
                invite_id = %d',
            mysql_real_escape_string($invite_id)
        ));
        if (!$result) {
            trigger_error(mysql_error, E_USER_WARNING);
            return FALSE;
        }
        if (!$row = mysql_fetch_assoc($result)) {
            return FALSE;
        }
        
        $this->id           = $row['invite_id'];
        $this->target_date  = $row['target_date'];
        $this->message      = $row['message'];
        $this->fixed        = $row['fixed'];
        $this->via          = $row['via'];
        $this->create_stamp = $row['create_stamp'];
        
        $result = mysql_query(sprintf('
            SELECT
                member_id,
                class,
                status,
                last_update
            FROM
                invite_members
            WHERE
                invite_id = %d',
            mysql_real_escape_string($invite_id)
        ));
        if (!$result) {
            trigger_error(mysql_error, E_USER_WARNING);
            return FALSE;
        }
        while ($row = mysql_fetch_assoc($result)) {
            if ($row['class'] == 'owner') {
                $this->owner_id     = $row['member_id'];
                $this->create_stamp = $row['last_update'];
            }
            else
                $this->members[] = array(
                    'member_id'   => $row['member_id'],
                    'status'      => $row['status'],
                    'last_update' => $row['last_update'],
                );
        }
        
        return;
    }
    
    function create () {
        if (!$this || !$this->owner_id) return FALSE;
        
        $dbh = DB::load_dbh();
        // start transaction
        $result = mysql_query(sprintf("
            INSERT INTO
                invites
            SET
                invite_id    = 0,
                target_date  = '%s',
                message      = '%s',
                create_stamp = NOW(),
                fixed        = 0,
                via          = '%s'",
            mysql_real_escape_string($this->target_date),
            mysql_real_escape_string($this->message),
            mysql_real_escape_string($this->via)
        ));
        if (!$result) {
            trigger_error(mysql_error, E_USER_WARNING);
            return FALSE;
        }
        $this->id = mysql_insert_id();
        
        $result = mysql_query(sprintf("
            INSERT INTO
                invite_members
            SET
                invite_id   = '%d',
                member_id   = '%d',
                class       = 'owner',
                status      = 'join',
                last_update = NOW()",
            mysql_real_escape_string($this->id),
            mysql_real_escape_string($this->owner_id)
        ));
        if (!$result) {
            trigger_error(mysql_error, E_USER_WARNING);
            return FALSE;
        }
        $this->create_stamp = date('Y-m-d h:i:s');
        
        return TRUE;
    }
    
    function fix () {
        if (!$this || !$this->id) return FALSE;
        
        $dbh = DB::load_dbh();
        $result = mysql_query(sprintf("
            UPDATE
                invites
            SET
                fixed = 1
            WHERE
                invite_id = '%d'",
            mysql_real_escape_string($this->id)
        ));
        if (!$result) {
            trigger_error(mysql_error, E_USER_WARNING);
            return FALSE;
        }
        
        if (!mysql_affected_rows())
            return FALSE;
        
        $this->fixed = 1;
        return TRUE;
    }
    
    function add ($member_id) {
        if (!$this || !$this->id || !$member_id) return FALSE;
        
        $dbh = DB::load_dbh();
        $result = mysql_query(sprintf("
            INSERT INTO
                invite_members
            SET
                invite_id   = '%d',
                member_id   = '%d',
                class       = 'invitee',
                status      = 'na',
                last_update = NOW()",
            mysql_real_escape_string($this->id),
            mysql_real_escape_string($member_id)
        ));
        if (!$result) {
            trigger_error(mysql_error, E_USER_WARNING);
            return FALSE;
        }
        $this->members[] = array(
            'member_id'   => $member_id,
            'status'      => 'na',
            'last_update' => date('Y-m-d h:i:s'),
        );
        return TRUE;
    }
    
    function check ($member_id) {
        if (!$this || !$this->id || !member_id) return FALSE;
        return $this->_update($member_id, 'check');
    }
    
    function join ($member_id) {
        if (!$this || !$this->id || !$member_id) return FALSE;
        return $this->_update($member_id, 'join');
    }
    
    function reject ($member_id) {
        if (!$this || !$this->id || !$member_id) return FALSE;
        return $this->_update($member_id, 'reject');
    }
    
    function _update ($member_id, $status) {
        if (!$this || !$this->id || !$member_id || !in_array($status, array('join', 'reject'))) return FALSE;
        
        $dbh = DB::load_dbh();
        $result = mysql_query(sprintf("
            UPDATE
                invite_members
            SET
                status      = '%s',
                last_update = NOW()
            WHERE
                invite_id = '%d' &&
                member_id = '%d' &&
                class     = 'invitee'",
            mysql_real_escape_string($status),
            mysql_real_escape_string($this->id),
            mysql_real_escape_string($member_id)
        ));
        if (!$result) {
            trigger_error(mysql_error, E_USER_WARNING);
            return FALSE;
        }
        if (!mysql_affected_rows())
            return;
        foreach ($this->members as &$member) {
            if ($member['member_id'] == $member_id)
                $member['status'] = $status;
        }
        return TRUE;
    }
    
    function delete () {
        if (!$this || !$this->id) return FALSE;
        
        $dbh = DB::load_dbh();
        $result = mysql_query(sprintf("
            DELETE FROM
                invites
            WHERE
                invite_id = '%d'
            LIMIT 1",
            mysql_real_escape_string($this->id)
        ));
        if (!$result) {
            trigger_error(mysql_error, E_USER_WARNING);
            return FALSE;
        }
        if (!mysql_affected_rows())
            return;

        $result = mysql_query(sprintf("
            DELETE FROM
                invite_members
            WHERE
                invite_id = '%d'",
            mysql_real_escape_string($this->id)
        ));
        if (!$tesult) {
            trigger_error(mysql_error, E_USER_WARNING);
            return FALSE;
        }
        
        unset($this->members);
        unset($this->owner_id);
        unset($this->id);
        return TRUE;
    }
    
    function get_list ($member_id, $all = 0) {
        if (!is_numeric($member_id)) return FALSE;
        
        $dbh = DB::load_dbh();
        $result = mysql_query(sprintf("
            SELECT
                invite_id AS id
            FROM
                invite_members
            WHERE
                member_id = %d &&
                status != 'reject'",
            mysql_real_escape_string($member_id)
        ));
        if (!$result) {
            trigger_error(mysql_error, E_USER_WARNING);
            return FALSE;
        }
        
        $invite_ids = array();
        while ($row = mysql_fetch_assoc($result))
            $invite_ids[$row['id']] = $row['id'];
        
        $ids = join(', ', array_keys($invite_ids));
        
        $base_date = $all ? '2000-01-01' : date('Y-m-d');
        
        $result = mysql_query(sprintf("
            SELECT
                invite_id AS id,
                target_date,
                message,
                create_stamp
            FROM invites
            WHERE
                invite_id IN (%s) &&
                fixed = 1 &&
                target_date >= '%s'",
            $ids,
            $base_date
        ));
        if (!$result) {
            trigger_error(mysql_error, E_USER_WARNING);
            return FALSE;
        }
        
        $invites = array();
        while ($row = mysql_fetch_assoc($result))
            $invites[$row['id']] = $row;
        $ids = join(', ', array_keys($invites));
        if (!$ids) return array();
        
        $result = mysql_query(sprintf("
            SELECT
                invite_id AS id,
                member_id,
                class,
                status,
                last_update
            FROM
                invite_members
            WHERE
                invite_id IN (%s)",
            $ids
        ));
        if (!$result) {
            trigger_error(mysql_error, E_USER_WARNING);
            return FALSE;
        }
        
        while ($row = mysql_fetch_assoc($result)) {
            if ($row['class'] == 'owner')
                $invites[$row['id']]['owner_id']     = $row['member_id'];
            else
                $invites[$row['id']]['members'][] = array(
                    'member_id'   => $row['member_id'],
                    'status'      => $row['status'],
                    'last_update' => $row['last_update'],
                );
        }
        return $invites;
    }
    
    function get_unseen_ids ($member_id) {
        if (!is_numeric($member_id)) return FALSE;
        
        $dbh = DB::load_dbh();
        $result = mysql_query(sprintf("
            SELECT
                invite_id AS id
            FROM
                invite_members
            WHERE
                member_id = %d &&
                status = 'na'",
            mysql_real_escape_string($member_id)
        ));
        if (!$result) {
            trigger_error(mysql_error, E_USER_WARNING);
            return;
        }
        $invite_ids = array();
        while ($row = mysql_fetch_assoc($result))
            $invite_ids[] = $row['id'];
        
        return $invite_ids;
    }
    
    function get_count_total () {
        $dbh = DB::load_dbh();
        $result = mysql_query('
            SELECT
                MAX(invite_id) AS count
            FROM
                invites
        ');
        if (!$result) {
            trigger_error(mysql_error, E_USER_WARNING);
            return;
        }
        if ($row = mysql_fetch_assoc($result))
            return $row['count'];
        return;
    }
    
    function get_count_all () {
        $dbh = DB::load_dbh();
        $result = mysql_query('
            SELECT
                via,
                COUNT(invite_id) AS count
            FROM
                invites
            GROUP BY
                via
        ');
        if (!$result) {
            trigger_error(mysql_error, E_USER_WARNING);
            return;
        }
        $count = array();
        while ($row = mysql_fetch_assoc($result))
            $count[$row['via']] = $row['count'];
        return $count;
    }
    
    function get_count_daily ($target_date) {
        if (!is_date($target_date)) return;
        $dbh = DB::load_dbh();
        $result = mysql_query(sprintf("
            SELECT
                via,
                COUNT(invite_id) AS count
            FROM
                invites
            WHERE
                create_stamp LIKE '%s%%'
            GROUP BY
                via
            ",
            mysql_real_escape_string($target_date)
        ));
        if (!$result) {
            trigger_error(mysql_error, E_USER_WARNING);
            return;
        }
        $count = array();
        while ($row = mysql_fetch_assoc($result))
            $count[$row['via']] = $row['count'];
        return $count;
    }
}
